package com.qqtech.qquan.community.controller;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.collect.Lists;
import com.qqtech.core.common.annotation.VisitAnnt;
import com.qqtech.core.common.enums.RespEnum;
import com.qqtech.core.common.enums.YesNoEnum;
import com.qqtech.core.common.util.StringUtil;
import com.qqtech.core.common.util.TimeUtil;
import com.qqtech.core.frame.model.PageKit;
import com.qqtech.core.frame.model.PageOrder;
import com.qqtech.core.frame.model.Result;
import com.qqtech.core.frame.service.BaseService;
import com.qqtech.qquan.activity.model.ActivityBaseQuery;
import com.qqtech.qquan.activity.model.ActivityBaseVo;
import com.qqtech.qquan.activity.service.ActivityBaseService;
import com.qqtech.qquan.activity.service.ActivitySignService;
import com.qqtech.qquan.ad.enums.AdTypeDictEnum;
import com.qqtech.qquan.ad.model.AdBaseVo;
import com.qqtech.qquan.ad.service.AdBaseService;
import com.qqtech.qquan.circle.enums.CircleAuditStatusEnum;
import com.qqtech.qquan.circle.enums.CircleBaseStatusDictEnum;
import com.qqtech.qquan.circle.enums.CircleOpenLevelDictEnum;
import com.qqtech.qquan.circle.model.CircleBaseQuery;
import com.qqtech.qquan.circle.model.CircleBaseVo;
import com.qqtech.qquan.circle.model.CircleInfoVo;
import com.qqtech.qquan.circle.service.CircleBaseService;
import com.qqtech.qquan.circle.service.CircleInfoService;
import com.qqtech.qquan.circle.service.CircleMemberService;
import com.qqtech.qquan.community.enums.CommunityConst;
import com.qqtech.qquan.community.enums.CommunityJoinStatusDictEnum;
import com.qqtech.qquan.community.model.CommunityBase;
import com.qqtech.qquan.community.model.CommunityBaseQuery;
import com.qqtech.qquan.community.model.CommunityBaseVo;
import com.qqtech.qquan.community.model.CommunityInfoVo;
import com.qqtech.qquan.community.model.CommunityJoinQuery;
import com.qqtech.qquan.community.model.CommunityJoinVo;
import com.qqtech.qquan.community.model.CommunityNoticeQuery;
import com.qqtech.qquan.community.model.CommunityNoticeVo;
import com.qqtech.qquan.community.model.CommunitySignQuery;
import com.qqtech.qquan.community.model.CommunitySysDict;
import com.qqtech.qquan.community.model.CommunitySysParamVo;
import com.qqtech.qquan.community.service.CommunityBaseService;
import com.qqtech.qquan.community.service.CommunityInfoService;
import com.qqtech.qquan.community.service.CommunityJoinService;
import com.qqtech.qquan.community.service.CommunityNoticeService;
import com.qqtech.qquan.community.service.CommunitySignService;
import com.qqtech.qquan.community.service.CommunitySysDictService;
import com.qqtech.qquan.community.service.CommunitySysParamService;
import com.qqtech.qquan.mall.enums.MallConst;
import com.qqtech.qquan.mall.enums.MallShopStyleDictEnum;
import com.qqtech.qquan.mall.service.MallShopService;
import com.qqtech.qquan.sys.model.SysAreaQuery;
import com.qqtech.qquan.sys.model.SysAreaVo;
import com.qqtech.qquan.sys.service.SysAreaService;
import com.qqtech.qquan.user.model.UserBase;
import com.qqtech.qquan.user.model.UserBaseQuery;
import com.qqtech.qquan.user.model.UserBaseVo;
import com.qqtech.qquan.user.model.UserMessage;
import com.qqtech.qquan.user.model.UserValueQuery;
import com.qqtech.qquan.user.model.UserValueVo;
import com.qqtech.qquan.user.service.UserBaseService;
import com.qqtech.qquan.user.service.UserFriendService;
import com.qqtech.qquan.user.service.UserMessageService;
import com.qqtech.qquan.user.service.UserPrivacyService;
import com.qqtech.qquan.user.service.UserValueService;
import com.qqtech.web.context.BaseWebController;

@Controller
@RequestMapping(value = "/community/base")
public class CommunityBaseController extends BaseWebController<CommunityBase, CommunityBaseQuery> {
	@Resource
	private CommunityBaseService communityBaseService;

	@Resource
	private CommunitySysDictService communitySysDictService;

	@Resource
	private CommunityInfoService communityInfoService;

	@Resource
	private CommunityNoticeService communityNoticeService;
	@Resource
	private UserFriendService userFriendService;

	@Resource
	private UserBaseService userBaseService;

	@Resource
	private CommunityJoinService communityJoinService;

	@Resource
	private CircleInfoService circleInfoService;

	@Resource
	private CommunitySignService communitySignService;

	@Resource
	private UserPrivacyService userPrivacyService;

	@Resource
	private SysAreaService sysAreaService;

	@Resource
	private UserMessageService userMessageService;

	@Resource
	private CommunitySysParamService communitySysParamService;

	@Resource
	private CircleBaseService circleBaseService;

	@Resource
	private CircleMemberService circleMemberService;

	@Resource
	private AdBaseService adBaseService;

	@Resource
	private ActivityBaseService activityBaseService;

	@Resource
	private ActivitySignService activitySignService;

	@Resource
	private MallShopService mallShopService;
	
	@Resource
	private UserValueService userValueService;

	private Integer TALENT_RANK = 3;//发帖达人
	private Integer MONTH_RANK = 2;//月榜
	private Integer WEEKLY_RANK = 1;//周榜
	private Integer HONOR_RANK = 0;//荣耀榜
	private Integer WEEKLY_DAY = 7;
	private Integer MONTH_DAY = 30;
	@Override
	protected BaseService<CommunityBase> getBaseService() {
		return communityBaseService;
	}

	/**
	 * 社区邻居
	 * 
	 * @param userBaseQuery
	 * @return
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/neighborPage")
	@ResponseBody
	public Result neighborPage(@RequestBody UserBaseQuery userBaseQuery) {
		Integer curUserId = super.getUserId();
		if(userBaseQuery.getCurrentClick() !=null){
			userBaseQuery.setCurrentClickTime(new Timestamp(userBaseQuery.getCurrentClick()*1000));
		}
		if(userBaseQuery.getLastClick() != null){
			userBaseQuery.setLastClickTime(new Timestamp(userBaseQuery.getLastClick()*1000));
		}
		Result result = new Result();
		// 用户
		boolean isJoin = communityJoinService.isJoinCommunity(userBaseQuery.getCommunityId(), curUserId);
		result.put("isJoin", isJoin);
		if (!isJoin) {
			return result;
		}
		//userBaseQuery.setId(curUserId);排除自己
		Pageable pageKit = new PageKit(userBaseQuery.getPage(), 20, new PageOrder(Direction.ASC, "isFriend"),
				new PageOrder(Direction.DESC, "id"));
		Page<UserBaseVo> page = userBaseService.queryPageNeighbor(userBaseQuery, pageKit);
		result.put("page", page);
		userBaseQuery.setIsFriend(YesNoEnum.YES.getCode());
		int friendCount = userBaseService.queryCountNeighbor(userBaseQuery);
		userBaseQuery.setIsFriend(YesNoEnum.NO.getCode());
		int otherCount = userBaseService.queryCountNeighbor(userBaseQuery);
		int isNewCount = userBaseService.queryCountNeighborIsNewByCommunityId(userBaseQuery);
		
		result.put("friendCount", friendCount);
		result.put("otherCount", otherCount-isNewCount);
		result.put("isNewCount", isNewCount);		
		return result;
	}

	/**
	 * 周边社区列表，根据距离排序分页
	 * 
	 * @param communityBaseQuery
	 * @return
	 */
	@RequestMapping(value = "/distancePage")
	@ResponseBody
	public Result distancePage(@RequestBody CommunityBaseQuery communityBaseQuery) {
		Result result = new Result();
		Integer curUserId = super.getUserId();
		if (StringUtil.isNotBlank(communityBaseQuery.getCityName())) {
			SysAreaQuery sysAreaQuery = new SysAreaQuery();
			sysAreaQuery.setNameAll(communityBaseQuery.getCityName());
			SysAreaVo sysAreaVo = sysAreaService.getOne(sysAreaQuery, new PageOrder(Direction.ASC, "id"));
			if (null != sysAreaVo) {
				communityBaseQuery.setCityId(sysAreaVo.getId());
			}
		}
		communityBaseQuery.setIsShow(YesNoEnum.YES.getCode());
		Pageable pageKit = new PageKit(communityBaseQuery.getPage(), new PageOrder(Direction.ASC, "distance"));
		Page<CommunityBaseVo> page = communityBaseService.queryDistancePage(communityBaseQuery, pageKit);
		for (CommunityBaseVo communityBaseVo : page) {
			if (null == communityBaseVo.getDistance()) {
				communityBaseVo.setDistance(BigDecimal.ZERO);
			}
		}
		// 我加入的社区
		CommunityBaseVo myCommunityBase=new CommunityBaseVo();
		if (null != curUserId) {
			UserBase userBase=userBaseService.getById(curUserId);
			if(null!=userBase.getCommunityId()){
				myCommunityBase=communityBaseService.getById(userBase.getCommunityId());
			}
		}
		result.put("myCommunityBase", myCommunityBase);
		result.put("page", page);
		return result;
	}

	/**
	 * 周边商家-搜索附近社区列表，根据距离排序分页
	 * 由搜索半径计算出来
	 * @param communityBaseQuery
	 * @return
	 */
	@RequestMapping(value = "/distancePage4MallShop")
	@ResponseBody
	public Result distancePage4MallShop(@RequestBody CommunityBaseQuery communityBaseQuery) {
		Result result = new Result();
		//距离半径
		Integer maxDistance = mallShopService.getServiceCommunityDistance(MallConst.PARAMKEY_MALL_SHOP_SERVICE_COMMUNITY_DISTANCE);
		communityBaseQuery.setMaxDistance(new BigDecimal(maxDistance));
		if (StringUtil.isNotBlank(communityBaseQuery.getCityName())) {
			SysAreaQuery sysAreaQuery = new SysAreaQuery();
			sysAreaQuery.setNameAll(communityBaseQuery.getCityName());
			SysAreaVo sysAreaVo = sysAreaService.getOne(sysAreaQuery, new PageOrder(Direction.ASC, "id"));
			if (null != sysAreaVo) {
				communityBaseQuery.setCityId(sysAreaVo.getId());
			}
		}
		communityBaseQuery.setIsShow(YesNoEnum.YES.getCode());
		Pageable pageKit = new PageKit(communityBaseQuery.getPage(), new PageOrder(Direction.ASC, "distance"));
		Page<CommunityBaseVo> page = communityBaseService.queryDistancePage(communityBaseQuery, pageKit);
		for (CommunityBaseVo communityBaseVo : page) {
			if (null == communityBaseVo.getDistance()) {
				communityBaseVo.setDistance(BigDecimal.ZERO);
			}
		}
		result.put("page", page);
		return result;
	}
	
	/**
	 * 周边社区列表
	 * 
	 * @param communityBaseQuery
	 * @return
	 */
	@RequestMapping(value = "/distanceList")
	@ResponseBody
	public Result distanceList(@RequestBody CommunityBaseQuery communityBaseQuery) {
		Result result = new Result();
		communityBaseQuery.setIsOpen(YesNoEnum.YES.getCode());
		Pageable pageKit = new PageKit(communityBaseQuery.getPage(), new PageOrder(Direction.ASC, "distance"));
		List<CommunityBaseVo> list = communityBaseService.queryDistanceList(communityBaseQuery, pageKit);
		result.put("list", list);
		return result;
	}

	/**
	 * 是否可以加入当前访问社区
	 * 
	 * @param communityId
	 * @return
	 */
	private boolean isJoin(Integer communityId, Integer curUserId) {
		boolean isJoin = false;
		isJoin = communityJoinService.isJoinCommunity(communityId, curUserId);
		if (isJoin) {// 已经加入当前访问社区
			return isJoin;
		}
		CommunityJoinQuery joinQuery = new CommunityJoinQuery();
		joinQuery.setUserId(curUserId);
		Integer quantity = 0;
		// 间隔天数
		CommunitySysParamVo daysVo = communitySysParamService.getByKey(CommunityConst.PARAMKEY_COMMUNITY_JOIN_DAYS);
		int days = Integer.valueOf(daysVo.getValue());
		// 最大加入数
		CommunitySysParamVo maxVo = communitySysParamService.getByKey(CommunityConst.PARAMKEY_COMMUNITY_JOIN_QUANTITY);
		int maxQuantity = Integer.valueOf(maxVo.getValue());

		joinQuery.setCommunityId(null);
		joinQuery.setStatus(null);
		quantity = communityJoinService.queryCount(joinQuery);// 加入社区记录数
		if (quantity < maxQuantity) {// 还未超过加入最大值
			return isJoin;
		}
		joinQuery.setStatus(CommunityJoinStatusDictEnum.NORMAL.getCode());
		quantity = communityJoinService.queryCount(joinQuery);// 加入社区正常的数量
		if (quantity < maxQuantity) {// 有退出社区的记录
			// 获取最后加入社区记录
			joinQuery.setStatus(CommunityJoinStatusDictEnum.QUIT.getCode());
			CommunityJoinVo firstJoinVo = communityJoinService.getFirstOne(joinQuery,
					new PageOrder(Direction.DESC, "id"));
			Timestamp admitJoinTime = TimeUtil.addDays(firstJoinVo.getNewAt(), days);
			if (TimeUtil.now().getTime() > admitJoinTime.getTime()) {// 大于最后一条加入社区时间，允许重新加入一个社区
				return isJoin;
			}
		}
		isJoin = true;// 已经最大加入社区了
		return isJoin;
	}

	/**
	 * 美丽家园
	 * 
	 * @param communityBaseQuery
	 * @return
	 */
	@RequestMapping(value = "/index")
	@ResponseBody
	public Result index(@RequestBody CommunityBaseQuery communityBaseQuery) {
		Result result = new Result();
		// 社区base
		CommunityBase communityBase = communityBaseService.getById(communityBaseQuery.getId());
		communityBase.setImgString(communityBase.getImg(), CommunityConst.IMG_POSTFIX);
		result.put("communityBase", communityBase);
		CommunityInfoVo cInfoVo = communityInfoService.getRowNumById(communityBaseQuery.getId());
		if (null != cInfoVo) {// 此社区根据上周活跃度的排名
			result.put("cInfoVo", cInfoVo);// 本社区
			Integer behindRowNum = cInfoVo.getRowNum() + 1;// 后一名
			Integer frontRowNum = cInfoVo.getRowNum() - 1;// 前一名
			CommunityInfoVo behindCInfoVo = communityInfoService.getRowNumByRowNum(behindRowNum);
			CommunityInfoVo frontCInfoVo = communityInfoService.getRowNumByRowNum(frontRowNum);
			if (null != behindCInfoVo) {// 后一名本社区
				CommunityBase behindCBase = communityBaseService.getById(behindCInfoVo.getId());
				result.put("behindCBase", behindCBase);// 后一名本社区
			}
			if (null != frontCInfoVo) {
				CommunityBase frontCBase = communityBaseService.getById(frontCInfoVo.getId());
				result.put("frontCBase", frontCBase);// 前一名本社区
			}

		}

		// 社区公告
		Pageable pageKit1 = new PageKit(1, 1, new PageOrder(Direction.DESC, "id"));
		CommunityNoticeVo notice = new CommunityNoticeVo();
		notice.setCommunityId(communityBaseQuery.getId());
		notice.setIsShow(YesNoEnum.YES.getCode());
		List<CommunityNoticeVo> noticeList = communityNoticeService.queryList(notice, pageKit1);
		if (null != noticeList && noticeList.size() > 0) {
			notice = noticeList.get(0);
		}
		result.put("notice", notice);

		// 5位用户
		CommunityJoinQuery communityJoinQuery = new CommunityJoinQuery();
		communityJoinQuery.setStatus(CommunityJoinStatusDictEnum.NORMAL.getCode());
		communityJoinQuery.setCommunityId(communityBaseQuery.getId());
		// 加入访问社区的用户list
		List<CommunityJoinVo> listJoin = communityJoinService.queryList(communityJoinQuery);
		if (null != listJoin && listJoin.size() > 0) {
			List<Integer> containIds = new ArrayList<Integer>();
			for (CommunityJoinVo communityJoinVo : listJoin) {
				containIds.add(communityJoinVo.getUserId());
			}
			UserBaseQuery userBaseQuery = new UserBaseQuery();
			userBaseQuery.setContainIds(containIds);
			Pageable pageKit2 = new PageKit(1, 5, new PageOrder(Direction.DESC, "id"));
			Page<UserBase> pageUser = userBaseService.queryPageList(userBaseQuery, pageKit2);
			result.put("userList", pageUser.getContent());

		}
		// 社区圈子
		CircleBaseQuery circleBaseQuery = new CircleBaseQuery();
		circleBaseQuery.setCommunityId(communityBaseQuery.getId());
		circleBaseQuery.setStatus(CircleBaseStatusDictEnum.NORMAL.getCode());
		circleBaseQuery.setAuditStatus(CircleAuditStatusEnum.AUDIT_PASS.getCode());
		Pageable pageKit3 = new PageKit(1, 5, new PageOrder(Direction.DESC, "id"));
		Page<CircleBaseVo> circlePage = circleBaseService.queryPageList(circleBaseQuery, pageKit3);
		result.put("circlePage", circlePage);

		return result;
	}

	/**
	 * 社区top列表
	 * 
	 * @param communityBaseQuery
	 * @return
	 */
	@RequestMapping(value = "/topList")
	@ResponseBody
	public Result topList(@RequestBody CommunityBaseQuery communityBaseQuery) {
		Result result = new Result();
		Integer curUserId = super.getUserId();

		List<CommunityBaseVo> list = new ArrayList<CommunityBaseVo>();
		CommunityBaseVo visitBaseVo = null;
		CommunityBaseQuery cBaseQuery = new CommunityBaseQuery();
		cBaseQuery.setIsShow(YesNoEnum.YES.getCode());
		cBaseQuery.setIsOpen(YesNoEnum.YES.getCode());
		List<Integer> filterIds = new ArrayList<Integer>();
		if (null != communityBaseQuery.getId()) {// 从周边社区访问了一个社区
			visitBaseVo = communityBaseService.getById(communityBaseQuery.getId());
			if (null != curUserId) {
				boolean isJoin2 = communityJoinService.isJoinCommunity(communityBaseQuery.getId(), curUserId);
				if (isJoin2) {
					visitBaseVo.setIsJoin(true);
				}
			}
			list.add(visitBaseVo);
			filterIds.add(communityBaseQuery.getId());
		}

		// 获取加入社区list
		List<CommunityJoinVo> joinList = null;
		if (null != curUserId) {
			CommunityJoinQuery communityJoinQuery = new CommunityJoinQuery();
			communityJoinQuery.setUserId(curUserId);
			communityJoinQuery.setStatus(CommunityJoinStatusDictEnum.NORMAL.getCode());
			joinList = communityJoinService.queryList(communityJoinQuery);
		}
		if (joinList == null || joinList.size() <= 0) {
			if (filterIds.size() > 0) {
				cBaseQuery.setFilterIds(filterIds);// 过滤访问id
			}
			Pageable pageKit = new PageKit(1, 3, new PageOrder(Direction.DESC, "id"));
			List<CommunityBaseVo> communityList = communityBaseService.queryList(cBaseQuery, pageKit);
			list.addAll(communityList);
		} else {// 加入的社区
			for (CommunityJoinVo communityJoinVo : joinList) {
				if (!communityJoinVo.getCommunityId().equals(communityBaseQuery.getId())) {
					CommunityBaseVo concernBaseVo = communityBaseService.getById(communityJoinVo.getCommunityId());
					concernBaseVo.setIsJoin(true);
					list.add(concernBaseVo);
				}
			}
		}
		boolean isJoin = false;// 是否可以加入当前社区
		boolean isSign = false;
		if (null != curUserId) {
			isJoin = isJoin(list.get(0).getId(), curUserId);
			// 当前社区是否已加入
			boolean isJoinThis = communityJoinService.isJoinCommunity(list.get(0).getId(), curUserId);
			result.put("isJoinThis", isJoinThis);// 市
			if (isJoinThis) {
				boolean isSignThis = communitySignService.isSign(curUserId, list.get(0).getId());
				if (!isSignThis) {
					isSign = true;
				}
			}
		}
		SysAreaVo cityArea = sysAreaService.getById(list.get(0).getCityId());
		SysAreaVo provinceArea = sysAreaService.getParentArea(list.get(0).getCityId());
		result.put("isSign", isSign);// 市
		result.put("cityArea", cityArea);// 市
		result.put("provinceArea", provinceArea);// 省
		result.put("isJoin", isJoin);// 是否可加入社区
		result.put("communityList", list);
		return result;
	}

	/**
	 * pv+1再获取社区详情
	 * 
	 * @param communityBaseQuery
	 * @return
	 */
	@RequestMapping(value = "/detail")
	@ResponseBody
	public Result detail(@RequestBody CommunityBaseQuery communityBaseQuery) {
		Result result = new Result();
		Integer curUserId = super.getUserId();
		Integer curUserCommunityId = null;
		UserBaseVo userBaseVo=userBaseService.getById(curUserId);
		curUserCommunityId=userBaseVo.getCommunityId();
		result.put("curUserCommunityId",curUserCommunityId);
		CommunityBase detail = communityBaseService.handleDetail(communityBaseQuery.getId());
		int neighborCount = 0;
		int circleCount = 0;
		int qShopCount = 0;
		CircleBaseQuery circleQuery = new CircleBaseQuery();
		circleQuery.setCommunityId(communityBaseQuery.getId());
		circleQuery.setAuditStatus(CircleAuditStatusEnum.AUDIT_PASS.getCode());// 审核通过的
		circleQuery.setStatus(CircleBaseStatusDictEnum.NORMAL.getCode());
		List<Integer> includeOpenLevelList = Lists.newArrayList();
		includeOpenLevelList.add(CircleOpenLevelDictEnum.FULL_OPEN.getCode());
		includeOpenLevelList.add(CircleOpenLevelDictEnum.HALF_OPEN.getCode());
		circleCount = circleBaseService.getCircleList4Community(communityBaseQuery.getId()).size();// 辐射这个社区的圈子数量
		qShopCount = mallShopService.getCountShopByCommunityId(communityBaseQuery.getId(),
				MallShopStyleDictEnum.LOCAL.getCode());
		// 是否加入社区、签到等
		String showCanJoinSign = "1";// 加入社区
		if (null != curUserId) {// 登陆
			boolean isJoin = communityJoinService.isJoinCommunity(communityBaseQuery.getId(), curUserId);
			if (isJoin) {
				boolean isSign = communitySignService.isSign(curUserId, communityBaseQuery.getId());
				if (!isSign) {
					showCanJoinSign = "2";// 签到
				} else {
					showCanJoinSign = "3";// 已签到
				}
			}
		}
		UserBaseQuery userBaseQuery = new UserBaseQuery();
		userBaseQuery.setCommunityId(communityBaseQuery.getId());
		//userBaseQuery.setId(curUserId);排除自己
		neighborCount = userBaseService.queryCountNeighbor(userBaseQuery);// 邻居数量
		
		UserValueQuery userValueQuery=new UserValueQuery();
		userValueQuery.setCommunityId(communityBaseQuery.getId());
		if(communityBaseQuery.getRankType() == TALENT_RANK){
			Pageable pageKit = new PageKit(userValueQuery.getPage(), userValueQuery.getSize(), new PageOrder(Direction.DESC, "c.mount") );
			Page<UserValueVo> page = userValueService.queryPageListByTalent(userValueQuery, pageKit);
			result.put("users", page.getContent());
			return result;
		}
		if(communityBaseQuery.getRankType() == WEEKLY_RANK || communityBaseQuery.getRankType() == MONTH_RANK){
			Date date = new Date();
			userValueQuery.setEndTime(new Timestamp(date.getTime()));
			userValueQuery.setStartTime(new Timestamp(subDate(date,WEEKLY_DAY).getTime()));
			if(communityBaseQuery.getRankType() == MONTH_RANK){
				userValueQuery.setStartTime(new Timestamp(subDate(date,MONTH_DAY).getTime()));
			}
			Pageable pageKit = new PageKit(1,6, new PageOrder(Direction.DESC, "honorValue"),new PageOrder(Direction.DESC, "u.id"));
			Page<UserValueVo> page = userValueService.queryUserInfo(userValueQuery, pageKit);
			result.put("users", page.getContent());
			return result;
		}
		
		Pageable pageKit = new PageKit(1,6, new PageOrder(Direction.DESC, "honorValue"),new PageOrder(Direction.DESC, "u.id"));
		Page<UserValueVo> page = userValueService.queryUserInfo(userValueQuery, pageKit);
		result.put("users", page.getContent());
		result.put("qShopCount", qShopCount);
		result.put("circleCount", circleCount);
		result.put("neighborCount", neighborCount);
		result.put("showCanJoinSign", showCanJoinSign);
		result.put("detail", detail);
		return result;
	}
	private Date subDate(Date date, int day) {
		Calendar c = Calendar.getInstance();
		c.setTimeInMillis(date.getTime() - ((long) day) * 24 * 3600 * 1000);
		return c.getTime();
	}
	/**
	 * 创建社区
	 * 
	 * @param communityBaseVo
	 * @return
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/create")
	@ResponseBody
	public Result create(@RequestBody CommunityBaseVo communityBaseVo) {
		Result result = new Result();
		Integer curUserId = super.getUserId();
		communityBaseVo.setCreatorId(curUserId);
		communityBaseVo.setAgentId(curUserId);
		communityBaseVo.setIsOpen(YesNoEnum.NO.getCode());
		communityBaseVo.setIsShow(YesNoEnum.NO.getCode());
		if (StringUtil.isNotBlank(communityBaseVo.getCityName())) {
			SysAreaQuery sysAreaQuery = new SysAreaQuery();
			sysAreaQuery.setNameAll(communityBaseVo.getCityName());
			SysAreaVo sysAreaVo = sysAreaService.getOne(sysAreaQuery, new PageOrder(Direction.ASC, "id"));
			if (null != sysAreaVo) {
				communityBaseVo.setCityId(sysAreaVo.getId());
			}
		}
		if (StringUtil.isNotBlank(communityBaseVo.getDistrictName())) {
			SysAreaQuery sysAreaQuery = new SysAreaQuery();
			sysAreaQuery.setNameAll(communityBaseVo.getDistrictName());
			SysAreaVo sysAreaVo = sysAreaService.getOne(sysAreaQuery, new PageOrder(Direction.ASC, "id"));
			if (null != sysAreaVo) {
				communityBaseVo.setDistrictId(sysAreaVo.getId());
			}
		}
		communityBaseVo.setLogo("");
		communityBaseService.addCommunityBase(communityBaseVo);
		return result;
	}

	/**
	 * 隐藏
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/hide")
	@ResponseBody
	public Result hide(@RequestBody Integer id) {
		Result result = new Result();
		communityBaseService.hide(id);
		return result;
	}

	// 为话题-附加 评论数量、点赞
	/**
	 * 
	 * @param userVo
	 *            留言者
	 * @param toUserId
	 *            被留言者id
	 */
	private void addUserMessage4User(UserBaseVo userVo, Integer toUserId) {
		UserMessage message = userMessageService.queryLastMessage(userVo.getId(), toUserId);
		UserMessage userMessage = new UserMessage();
		userMessage.setToId(userVo.getId());
		int userMessageQuantity = userMessageService.queryCount(userMessage);
		userVo.setUserMessageQuantity(userMessageQuantity);
		if (message != null) {
			userVo.setMessage(message.getContent());
			userVo.setShowMsg(true);
		} else {
			userVo.setMessage("");
			userVo.setShowMsg(false);
		}
	}

	/**
	 * 新社区index
	 * 
	 * @param
	 * @return
	 */
	@RequestMapping(value = "/indexNew")
	@ResponseBody
	public Result indexNew(@RequestBody Map<String, String> map) {
		Result ret = new Result();
		Integer curUserId = super.getUserId();
		Integer curUserCommunityId = null;
		// 社区index头部社区列表 start
		Integer communityId = null;
		if (StringUtil.isNotBlank(map.get("communityId"))) {
			communityId = Integer.valueOf(map.get("communityId"));
		}
		BigDecimal x = null;
		if (StringUtil.isNotBlank(map.get("dingweiX"))) {
			x = new BigDecimal(map.get("dingweiX"));
		}
		BigDecimal y = null;
		if (StringUtil.isNotBlank(map.get("dingweiY"))) {
			y = new BigDecimal(map.get("dingweiY"));
		}
		CommunityBaseVo communityBaseVo = null;
		if (null != communityId) {// 从周边社区访问了一个社区
			communityBaseVo = communityBaseService.getById(communityId);
			communityBaseVo.setTxtShow(true);
		}else{
			CommunityBaseQuery query=new CommunityBaseQuery();
			query.setIsShow(YesNoEnum.YES.getCode());
			query.setIsOpen(YesNoEnum.YES.getCode());
			if(null!=x&&null!=y){
				query.setX(x);
				query.setY(y);
				Pageable pageKit = new PageKit(1, 1,new PageOrder(Direction.ASC, "distance"));
				List<CommunityBaseVo> list = communityBaseService.queryDistanceList(query, pageKit);
				communityBaseVo=list.get(0);
			}else{
				Pageable pageKit1 = new PageKit(1, 1, new PageOrder(Direction.ASC, "newAt"));
				List<CommunityBaseVo> list=communityBaseService.queryList(query,pageKit1);
				communityBaseVo=list.get(0);
			}
			communityBaseVo.setTxtShow(true);
		}
		if(null!=curUserId){
			UserBaseVo userBaseVo=userBaseService.getById(curUserId);
			curUserCommunityId=userBaseVo.getCommunityId();
			if(null!=userBaseVo.getCommunityId()){
				if(null!=communityId){
					if(communityId.intValue()==userBaseVo.getCommunityId()){
						communityBaseVo.setTxtShow(false);
					}
				}else{
					communityBaseVo=communityBaseService.getById(userBaseVo.getCommunityId());
					communityBaseVo.setTxtShow(false);
				}
			}
		}
		communityId=communityBaseVo.getId();
		ret.put("curUserCommunityId", curUserCommunityId);
		ret.put("communityBaseVo", communityBaseVo);
		// 社区index头部社区列表 end

		// 社区index广告 start
		List<AdBaseVo> crollbannerList = new ArrayList<AdBaseVo>();
		if (StringUtil.isNotBlank(communityBaseVo.getImg())) {
			String[] imgs = communityBaseVo.getImg().split(";");
			for (String string : imgs) {
				AdBaseVo adBaseVo = new AdBaseVo();
				adBaseVo.setImg(string);
				crollbannerList.add(adBaseVo);
			}
		}
		List<AdBaseVo> crollbannerListT = adBaseService.getAdListByType(AdTypeDictEnum.COMMUNITY,communityId);
		crollbannerList.addAll(crollbannerListT);
		ret.put("crollbannerList", crollbannerList);
		// 社区index广告 end

		// uiList start
		int neighborCount = 0;
		int circleCount = 0;
		int qShopCount = 0;
		UserBaseQuery userBaseQuery = new UserBaseQuery();
		userBaseQuery.setCommunityId(communityId);
		//userBaseQuery.setId(curUserId);排除自己
		neighborCount = userBaseService.queryCountNeighbor(userBaseQuery);// 邻居数量
		circleCount = circleBaseService.getCircleList4Community(communityId).size();// 辐射这个社区
																					// 的圈子数量
		qShopCount = mallShopService.getCountShopByCommunityId(communityId, MallShopStyleDictEnum.LOCAL.getCode());
		ret.put("qShopCount", qShopCount);
		ret.put("circleCount", circleCount);
		ret.put("neighborCount", neighborCount);
		// 社区公告
		Pageable pageKit1 = new PageKit(1, 5, new PageOrder(Direction.DESC, "id"));
		CommunityNoticeQuery communityNoticeQuery = new CommunityNoticeQuery();
		communityNoticeQuery.setCommunityId(communityId);
		communityNoticeQuery.setIsShow(YesNoEnum.YES.getCode());
		List<CommunityNoticeVo> noticeList = communityNoticeService.queryList(communityNoticeQuery, pageKit1);
		ret.put("noticeList", noticeList);

		// 社区推荐活动
		Pageable pageKit2 = new PageKit(1, 8, new PageOrder(Direction.ASC, "recommendOidx"),
				new PageOrder(Direction.ASC, "status"));
		ActivityBaseQuery activityBaseQuery = new ActivityBaseQuery();
		activityBaseQuery.setIsShow(YesNoEnum.YES.getCode());
		activityBaseQuery.setIsRecommend(YesNoEnum.YES.getCode());
		activityBaseQuery.setCommunityId(communityId);
		List<ActivityBaseVo> activityList = activityBaseService.queryList(activityBaseQuery, pageKit2);
		if (null == activityList || activityList.size() <= 0) {
			activityBaseQuery.setIsRecommend(null);
			pageKit2 = new PageKit(1, 8, new PageOrder(Direction.ASC, "status"), new PageOrder(Direction.DESC, "id"));
			activityList = activityBaseService.queryList(activityBaseQuery, pageKit2);
		}
		int signCount = 0;
		for (ActivityBaseVo activityBaseVo : activityList) {
			signCount = activitySignService.getSignCount(activityBaseVo.getId());
			activityBaseVo.setSignCount(signCount);
		}
		ret.put("activityList", activityList);

		// 社区话题tag
		List<CommunitySysDict> tagList = new ArrayList<CommunitySysDict>();
		CommunitySysDict communitySysDict = new CommunitySysDict();
		communitySysDict.setId(-1);
		communitySysDict.setName("全部分类");
		tagList.add(communitySysDict);
		List<CommunitySysDict> tagListT = communitySysDictService.get(CommunityConst.DICTYPE_COMMUNITY_MESSAGE_TAG);
		tagList.addAll(tagListT);
		ret.put("tagList", tagList);

		List<CommunitySysDict> tagListSign = communitySysDictService.get(CommunityConst.DICTYPE_COMMUNITY_SIGN_TEXT);
		ret.put("signText", tagListSign.get(0).getName());
		List<CircleBaseVo> circleBaseList = circleBaseService.getRecommendCircleList(communityId, 8);
		CircleInfoVo circleInfoVoTemp = null;
		for (CircleBaseVo circleBaseVo : circleBaseList) {
			circleInfoVoTemp = circleInfoService.getById(circleBaseVo.getId());
			if (circleInfoVoTemp != null) {
				circleBaseVo.setMemberCount(circleInfoVoTemp.getMemberCount());// 成员数量
			} else {
				circleBaseVo.setMemberCount(0);
			}
		}
		ret.put("circleBaseList", circleBaseList);
		// 是否加入社区、签到等
		String showCanJoinSign = "1";// 加入社区
		if (null != curUserId) {// 登陆
			boolean isJoin = communityJoinService.isJoinCommunity(communityId, curUserId);
			if (isJoin) {
				CommunitySignQuery communitySignQuery = new CommunitySignQuery();
				communitySignQuery.setUserId(curUserId);
				communitySignQuery.setNewAt(TimeUtil.now());
				int count = communitySignService.queryCount(communitySignQuery);
				if(count<=0){
					showCanJoinSign = "2";// 签到
				}else{
					showCanJoinSign = "3";// 已签到
				}
			}
		}
		ret.put("showCanJoinSign", showCanJoinSign);
		//社区新邻居
		if(map.get("currentClick") !=null){
			userBaseQuery.setCurrentClickTime(new Timestamp(Long.parseLong(map.get("currentClick"))*1000));
		}
		if(map.get("lastClick") !=null){
			userBaseQuery.setLastClickTime(new Timestamp(Long.parseLong(map.get("lastClick"))*1000));
		}
		int newNeighborCount = userBaseService.queryCountNeighborIsNewByCommunityId(userBaseQuery);
		ret.put("newNeighborCount", newNeighborCount);
		// uiList end
		return ret;
	}

	@RequestMapping(value = "/list")
	@ResponseBody
	public Result list(@RequestBody CommunityBaseQuery query) {
		Result ret = new Result();
		query.setIsShow(YesNoEnum.YES.getCode());
		query.setIsOpen(YesNoEnum.YES.getCode());
		Pageable pageKit2 = new PageKit(query.getPage(), new PageOrder(Direction.DESC, "id"));
		Page<CommunityBaseVo> page = communityBaseService.queryPageList(query, pageKit2);
		ret.put("page", page);
		return ret;
	}

	@RequestMapping(value = "/allList")
	@ResponseBody
	public Result allList(@RequestBody CommunityBaseQuery query) {
		Result ret = new Result();
		query.setIsShow(YesNoEnum.YES.getCode());
		query.setIsOpen(YesNoEnum.YES.getCode());
		Pageable pageKit2 = new PageKit(query.getPage(), new PageOrder(Direction.DESC, "id"));
		List<CommunityBaseVo> list = communityBaseService.queryList(query, pageKit2);
		ret.put("list", list);
		return ret;
	}
}
